package self.hoy.demo.grainmall.product.xpt;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import self.hoy.demo.common.exception.BizCodeEnum;
import self.hoy.demo.common.utils.R;

import java.util.HashMap;
import java.util.Map;

/**
 * @author hyh
 * @date 2020/7/16
 */
@Slf4j
@RestControllerAdvice(basePackages = "self.hoy.demo.grainmall.product.controller")
//@ControllerAdvice(basePackages = "self.hoy.demo.grainmall.product.controller")
public class ProductControllerAdvice {

//    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
//    public R handleValidException (Exception e) {
    public R handleValidException (MethodArgumentNotValidException e) {
//        log.error("数据校验异常{}，异常类型：{}", e.getMessage(), e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        result.getFieldErrors().forEach((item)->{
            String fieldName = item.getField();
            String message = item.getDefaultMessage();
            map.put(fieldName, message);
        });
        return R.error(BizCodeEnum.INVALID.getCode(), BizCodeEnum.INVALID.getMsg()).put("data", map);
    }

    @ExceptionHandler(value = Exception.class)
    public R handler(Exception e) {
        e.printStackTrace();
        return R.error(BizCodeEnum.UNKNOWN.getCode(), BizCodeEnum.UNKNOWN.getMsg());
    }
}
